package com.gaowl.gulimall.product.service.impl;

import com.gaowl.common.to.SkuReductionTo;
import com.gaowl.common.to.SpuBoundsTo;
import com.gaowl.common.utils.R;
import com.gaowl.gulimall.product.feign.CouponFeignService;
import com.gaowl.gulimall.product.service.*;
import com.gaowl.gulimall.product.vo.BaseAttrs;
import com.gaowl.gulimall.product.vo.Skus;
import com.gaowl.gulimall.product.vo.SpuSaveVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaowl.common.utils.PageUtils;
import com.gaowl.common.utils.Query;

import com.gaowl.gulimall.product.dao.SpuInfoDao;
import com.gaowl.gulimall.product.entity.SpuInfoEntity;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        // 模糊查询
        // select * from pms_spu_info where brandId = ? and publish_status = ? and catelog_id = ?
        //  and (id=key or spu_name like %key%)

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and(w-> w.like("spu_name", key).or().eq("id", key));
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)){
            queryWrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)){
            queryWrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), queryWrapper
        );
        return new PageUtils(page);
    }


    /**
     * 保存商品的Spu信息
     * @param spuSaveVo 待保存的spu信息
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1.保存Spu基本信息  pms_spu_info
        SpuInfoEntity curSpuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, curSpuInfoEntity);
        curSpuInfoEntity.setCreateTime(new Date());
        curSpuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.insert(curSpuInfoEntity);  // 保存完成后，spu的id会自动封装到spuInfoEntity中
        Long curSpuId = curSpuInfoEntity.getId();

        // 2.保存Spu的描述 pms_spu_info_desc
        List<String> descript = spuSaveVo.getDescript();
        spuInfoDescService.saveSpuInfoDesc(curSpuId, descript);

        // 3.保存SPu的图片集 pms_spu_images
        List<String> spuImages = spuSaveVo.getImages();
        spuImagesService.batchSaveSpuImages(curSpuId, spuImages);

        // 4.保存SPu的规格参数  pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        productAttrValueService.batchSaveSpuBaseAttrs(curSpuId, baseAttrs);

        // 5.保存积分信息  gulimall_sms -> sms_spu_bounds
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo(curSpuId, spuSaveVo.getBounds().getBuyBounds(),
                spuSaveVo.getBounds().getGrowBounds());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0){
            log.error("远程调用gulimall_coupon服务，保存spu积分信息失败..");
        }

        // 6.保存当前Spu对应的所有sku信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(sku -> {
                // 6.1 sku的基本信息 pms_sku_info
                Long skuId = skuInfoService.saveBaseSkuInfo(sku, curSpuInfoEntity);
                // 6.2 sku的图片信息 pms_sku_images
                skuImagesService.batchSaveSkuImages(skuId, sku.getImages());
                // 6.3 sku的销售属性 pms_sku_sale_attr_value
                skuSaleAttrValueService.batchSaveSkuSaleAttrs(skuId, sku.getAttr());

                // 6.4 sku的优惠、满减等信息 gulimall_sms -> sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                if (sku.getFullCount() > 0 ||
                        (sku.getFullPrice().compareTo(new BigDecimal("0")) == 1)){
                    SkuReductionTo skuReductionTo = new SkuReductionTo();
                    BeanUtils.copyProperties(sku, skuReductionTo);
                    skuReductionTo.setSkuId(skuId);

                    R r2 = couponFeignService.saveSkuReductionTo(skuReductionTo);
                    if (r2.getCode() != 0){
                        log.error("远程调用gulimall_coupon服务，保存sku优惠信息失败..");
                    }
                }
            });
        }

    }
}